package chess

import (
	"encoding/json"
	"errors"
	"fmt"
	"log"
	"regexp"
	"strconv"
)

func NewGame() *Chessboard {
	return CreateChessboard()
}

// MovePiece 通过(1,1)(2,2)
func (c *Chessboard) MovePiece(inMsg, color string) (msg string, err error) {
	pointAt, pointTo, err := String2Point(inMsg)

	fmt.Println("存在非法输入")
	if err != nil {
		return fmt.Sprintf("%s", err), err
	}
	if val, ok := c.M[pointAt]; ok {
		if color == "system" { //系统用，不对外调用
			return val.MoveTo(pointTo)
		}
		if val.(*Piece).Color != color {
			return "这不是你的子", errors.New("这不是你的子")
		}
		return val.MoveTo(pointTo)
	}
	return "", errors.New("此点无法控制")
}

func (c *Chessboard) ChessboardRes() string {
	res := new(RespChess)
	res.Status = make([]PointAndChess, 0)
	for k, v := range c.M {
		//fmt.Println(m)
		res.Status = append(res.Status, PointAndChess{
			Point: k,
			Chess: fmt.Sprintf("%s", v.(*Piece).Name),
		})
	}
	marshal, err := json.Marshal(res)
	if err != nil {
		log.Println(err)
		return ""
	}
	return string(marshal)
}

func String2Point(s string) (point1, point2 Point, err error) {
	buf := s
	defer func() {
		if msg := recover(); msg != nil {
			err = errors.New("非法输入")
		}
	}()
	//解析正则表达式，如果成功返回解释器
	reg1 := regexp.MustCompile(`\d+`)
	//根据规则提取关键信息
	result1 := reg1.FindAllStringSubmatch(buf, -1)
	num1, _ := strconv.Atoi(result1[0][0])
	num2, _ := strconv.Atoi(result1[1][0])
	num3, _ := strconv.Atoi(result1[2][0])
	num4, _ := strconv.Atoi(result1[3][0])
	p1, p2 := new(Point), new(Point)
	p1.Line = num1
	p1.Row = num2
	p2.Line = num3
	p2.Row = num4
	return *p1, *p2, err
}
